package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.entity.Result;
import com.itheima.health.entity.ValidateCode;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.MemberService;

import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.OrderDto;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.util.Code2RedisUtils;
import com.itheima.health.util.ParseDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderSettingService orderSettingService;
    @Autowired
    private Code2RedisUtils code2RedisUtils;

    @Override
    @Transactional
    public Result addOrder(Map map) {
        Object setmealId = map.get("setmealId");
        Object sex = map.get("sex");
        String name = (String) map.get("name");
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String idCard = (String) map.get("idCard");
        String orderDateStr = (String) map.get("orderDate");

        //0.setmealId 必须存在 逻辑外键这里就不写了
        //1.判断日期必须填写
        if (!StringUtils.hasLength(orderDateStr)) {
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }

        //1.1将Date进行格式转换;Order的java对象orderDate属性是Date类型
        Date orderDate = null;
        try {
            orderDate = ParseDateUtils.parseDate("yyyy-MM-dd", orderDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //1.2创建sql date;order表的orderDate字段是date类型
        java.sql.Date orderDate_sql = new java.sql.Date(orderDate.getTime());
        //2.验证码验证
        ValidateCode key = new ValidateCode("ORDER", Long.parseLong(telephone));
        String codeInRedis = code2RedisUtils.findRedis(key);
        if (!codeInRedis.equals(validateCode) || !StringUtils.hasLength(codeInRedis)) {
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }

        //3.判断是不是老会员 不能重复预约
        Member member = memberService.getMemberByPhone(telephone);
        if (member == null) {
            //3.1 没注册会员呢.自动注册会员
            member = new Member();
            member.setName(name);
            member.setSex(sex + "");
            member.setIdCard(idCard);
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.addMember(member);
        } else {
            //3.1老会员了,信息可能有更新,
            member.setName(name);
            member.setSex(sex + "");
            member.setIdCard(idCard);
            memberService.updateMember(member);
            //3.2从预约表里查询 这个人 这一天 这一个套餐是不是已经预约了
            Long count = orderDao.selectCountByCOndition(member.getId(), Integer.parseInt(setmealId+""), orderDate_sql);
            if (count > 0) {
                throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
            }
        }

        //4.判断预约信息 ordersetting表的number字段
        OrderSetting orderSetting = orderSettingService.getOrderByDate(orderDate_sql);
        log.info("****orderSetting信息:{}",orderSetting);
        if (orderSetting == null){
            //这一天未设置预约信息
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        Integer restCount = orderSetting.getNumber() - orderSetting.getReservations();
        log.info("*****剩余预约数量:{}",restCount);
        if (restCount <= 0) {
            //预约已满
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        //5.拼一个order出来 insert
        Order order = new Order(member.getId(), orderDate_sql, "微信预约", "未到诊", Integer.parseInt(setmealId+""));
        orderDao.addOrder(order);
        //6.删除redis中的验证码
        code2RedisUtils.deleteRedis(key);
        //7.预约成功,那么ordersetting表剩余数量需要变更
        orderSettingService.incrReservation(orderDate_sql);
        return new Result(true,MessageConst.ORDER_SUCCESS,order);
    }
    @Autowired
    private SetMealDao setMealDao;
    @Override
    public OrderDto findById(Integer id) {
        log.info("根据体检预约id查询体检预约单id:{}",id);
        Order order = orderDao.findByOrderId(id);
        Integer memberId = order.getMemberId();
        //根据order获得setmeal的id
        Integer setmealId = order.getSetmealId();
        Setmeal setmeal = setMealDao.selectBySetMealId(setmealId);
        OrderDto orderDto= new OrderDto();
        Member member = orderDao.findByMemberId(memberId);
        //给前端的orderDto空属性赋值
        orderDto.setMember(member.getName());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getOrderDate());
        String dateStr = calendar.get(Calendar.YEAR) + "-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DATE);
        orderDto.setOrderDate(dateStr);
        orderDto.setOrderType(order.getOrderType());
        orderDto.setSetmeal(setmeal.getName());
        return orderDto;
    }
}
